/*
CpGears v1.0

Copyright (c) 2010 Yves Riel http://www.flash-factor.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cpgears.movie.variables.monitor {
	import cpgears.helpers.StringUtil;
	import cpgears.log.ILogger;
	import cpgears.log.LogManager;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	/**
	 * Monitors variables of a DisplayObject for changes.
	 * 
	 * <P>The monitor will attach itself to the timeline and verify for changes
	 * on every frame.</P>
	 * 
	 * @author Whyves
	 */
	public class VariableMonitor extends EventDispatcher {
		
		public static const VARIABLE_CHANGED:String = "variableChanged";
		
		private var mSource:DisplayObject = null;
		private var mLogger:ILogger = null;
		private var mMonitorTargets:Object = {};
		private var mMonitoredCount:uint = 0;
		
		/**
		 * Creates a monitor.
		 * @param	source The DisplayObject that will be monitored.
		 */
		public function VariableMonitor(source:DisplayObject) {
			if (source == null) throw new ArgumentError("The 'source' parameter cannot be null");
			mSource = source;
			mLogger = LogManager.getLogger(this);
		}
		
		/**
		 * Adds a variable to the monitoring list.
		 * 
		 * @param	variableName The name of the variable to monitor.
		 */
		public function addVariable(variableName:String):void {
			if (StringUtil.isNullOrEmpty(variableName) || mMonitorTargets.hasOwnProperty(variableName)) return;
			if (mMonitoredCount == 0) attachToTimeline();
			
			if (mSource.hasOwnProperty(variableName)) {
				var monitoredVariable:MonitoredVariable = new MonitoredVariable(variableName);
				monitoredVariable.setValue(mSource[variableName]);
				mMonitorTargets[variableName] = monitoredVariable;
				mMonitoredCount++;
			} else {
				mLogger.warn("Variable '{0}' does not exist in DisplayObject '{1}'. No monitor was attached.", variableName, mSource.name);
			}
		}
		
		/**
		 * Removes a variable from the monitoring list.
		 * 
		 * @param	variableName The name of the variable to stop monitoring.
		 */
		public function removeVariable(variableName:String):void {
			if (StringUtil.isNullOrEmpty(variableName)) return;
			
			if (mMonitorTargets.hasOwnProperty(variableName)) {
				delete mMonitorTargets[variableName];
				mMonitoredCount--;
			} else {
				mLogger.warn("Variable '{0}' does not exist in DisplayObject '{1}'. Monitor was not removed.", variableName, mSource.name);
			}
			
			if (mMonitoredCount == 0) detachFromTimeline();
		}
		
		/**
		 * Returns the number of variables being monitored.
		 */
		public function get variablesCount():uint {
			return mMonitoredCount;
		}
		
		/**
		 * @private
		 */
		private function attachToTimeline():void {
			mSource.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		/**
		 * @private
		 */
		private function detachFromTimeline():void {
			mSource.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		/**
		 * @private
		 */
		private function onEnterFrame(event:Event):void {
			var variableValue:* = null;
			for each (var variable:MonitoredVariable in mMonitorTargets) {
				variableValue = mSource[variable.name];
				if (variable.value != variableValue) {
					variable.setValue(variableValue);
					dispatchEvent(new MonitoredVariableEvent(VARIABLE_CHANGED, variable));
				}
			}
		}
	}
}

